package com.mashibing.juc.c_026_01_ThreadPool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author: Yuanzt
 * @Date: 2021/4/2
 */
public class T06_00_Future {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        /*FutureTask实现了RunnableFuture接口，
        RunnableFuture继承了Runnable和Future两个接口，
        FutureTask既可以作为runnable又可以作为Future*/
        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println("等半秒");
            TimeUnit.MILLISECONDS.sleep(500);
            return 1000;
        });
        new Thread(task).start();
        System.out.println(task.get());


        ExecutorService service = Executors.newFixedThreadPool(5);
        Future<Integer> f = service.submit(() -> {
            System.out.println("等半秒");
            TimeUnit.MILLISECONDS.sleep(500);
            return 1;
        });//异步，异步表示，把任务交给这个线程。主线程该干嘛干嘛
        System.out.println(f.get());//f.get()方法会阻塞，知道有结果，f.get()才返回
        System.out.println(f.isDone());
        service.shutdown();//用完之后把线程放回到线程池
    }
}
